package cn.ddiancan.xddcloud.psc.base.service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import cn.ddiancan.xddcloud.psc.base.domain.OrganizationVO;
import com.alibaba.fastjson.JSON;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

@Service
public class OrganizationService {

    private static final String QICHACHA_ORGINAZATION_URL = "http://open.api.tianyancha.com/services/open/search/2.0";

    private static final String QICHACHA_ORGINAZATION_TOKEN = "bafc6c20-6cd0-4fd9-bdc5-4f52c48aa774";

    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取企业信息
     *
     * @param orgWord  企业名称，模糊
     * @param pageSize 每页条数
     * @param pageNo   页码
     * @return List<OrganizationVO>
     */
    @SuppressWarnings("unchecked")
    public List<OrganizationVO> getOrginazation(String orgWord, int pageSize, int pageNo) {
        HttpHeaders httpHeaders = new HttpHeaders();
        UriComponentsBuilder uriComponents = UriComponentsBuilder.fromHttpUrl(QICHACHA_ORGINAZATION_URL);
        uriComponents.queryParam("word", orgWord);
        uriComponents.queryParam("pageSize", pageSize);
        uriComponents.queryParam("pageNum", pageNo);
        UriComponents build = uriComponents.build();
        httpHeaders.add("Authorization", QICHACHA_ORGINAZATION_TOKEN);
        ParameterizedTypeReference<Map<String, Object>> typeReference = new ParameterizedTypeReference<>() {
        };
        ResponseEntity<Map<String, Object>> exchange =
            restTemplate.exchange(build.toString(), HttpMethod.GET, new HttpEntity<>(httpHeaders), typeReference);
        Map<String, Object> exchangeBody = exchange.getBody();
        if (CollectionUtils.isEmpty(exchangeBody)) {
            return Collections.emptyList();
        }
        Map<String, Object> result = (Map<String, Object>) exchangeBody.get("result");
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return JSON.parseArray(JSON.toJSONString(result.get("items")), OrganizationVO.class);
    }
}
